import logging
import os.path
import shutil
import time
from datetime import datetime

from tool import mns_time


class Log:
    record_dir = ""

    @classmethod
    def mns_logging(cls):
        logging.basicConfig(
            level = logging.INFO,
            format = "%(asctime)s - %(levelname)s - %(message)s",
        )

    # filename='app.log', # 日志文件名，如果没有这个参数，日志输出到console
    # filemode='w') # 文件写入模式，“w”会覆盖之前的日志，“a”会追加到之前的日志
    @classmethod
    def init_log(cls, file_name):
        # 创建新的文件夹记录信息
        record_dir = os.path.join("./log/log_file", str(datetime.now().strftime("%Y-%m-%d-%H-%M-%S")))
        cls.record_dir = record_dir
        os.makedirs(record_dir)
        # 拷贝配置文件
        if os.path.isfile(file_name):
            shutil.copy(file_name, os.path.join(record_dir, os.path.basename(file_name)))

    @classmethod
    def performance_log(cls):
        """性能记录日志"""
        logger = logging.getLogger("performance_logger")
        logger.setLevel(logging.INFO)
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        # 文件处理器
        file_handler = logging.FileHandler(os.path.join(cls.record_dir, 'performance.log'), mode = "w",
                                           encoding = "utf8")
        file_handler.setLevel(logging.INFO)
        # # 设置变量
        context_filter = ContextFilter('sim_time', cls.get_time)
        logger.addFilter(context_filter)
        # 格式处理器
        formatter = logging.Formatter("%(sim_time)s - PERF - %(message)s")
        # 将格式化器添加到处理器
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)

        # 将处理器添加到日志记录器
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)
        return logger

    @classmethod
    def ship_track_log(cls):
        logger = logging.getLogger("track_logger")
        logger.setLevel(logging.INFO)
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        # 文件处理器
        file_handler = logging.FileHandler(os.path.join(cls.record_dir, 'track.log'), mode = "w",
                                           encoding = "utf8")
        file_handler.setLevel(logging.INFO)
        # # 设置变量
        context_filter = ContextFilter('sim_time', cls.get_time)
        logger.addFilter(context_filter)
        # 格式处理器
        formatter = logging.Formatter("%(sim_time)s - TRACK - %(message)s")
        # 将格式化器添加到处理器
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)

        # 将处理器添加到日志记录器
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)
        return logger

    @classmethod
    def get_time(cls):
        return int(mns_time.Time.sim_time)


class ContextFilter(logging.Filter):
    def __init__(self, var_name, var_getter):
        super().__init__()
        self.var_name = var_name
        self.var_getter = var_getter

    def filter(self, record):
        setattr(record, self.var_name, self.var_getter())
        return True
